<?php 
error_reporting(E_ERROR);
session_start();
require_once('constants_shop.php');
require_once('functions.php');
include('classes/userClass.php');



#conect to shop database	
$shopObj = new mysqlClass();

// get active lang

$available_lang= $shopObj->fetch_result("SELECT * FROM languages WHERE is_default=1 LIMIT 1");
$active_lang = $available_lang[0]['id'];
//get dictionary
$dictionary = get_dictionary_shop($active_lang);

if(isset($_POST['get_properties'])){
	$params = array($_POST['get_properties'],$active_lang);
	$properties = $shopObj->fetch_result("SELECT properties_values.id, properties_values_details.name  FROM properties_values,properties_values_details WHERE properties_values.property_id=?
		AND properties_values.id = properties_values_details.property_value_id AND language_id=?",$params);
	echo '<div class="control-group">
	<label class="control-label span3" for="properties_'.$_POST['get_properties'].'">Select values</label>
	<div class="controls span9">';
	echo '<select multiple="" class="chzn-select" name="properties_'.$_POST['get_properties'].'"   data-placeholder="Choose properties values...">';
	foreach ($properties as $key => $value) {
		echo "<option value='{$value['id']}'>{$value['name']}</option>";
	}
	echo '</select><br /><button class="add_property_value btn btn-minier btn-success" style="margin-top:10px">+Add property value</button>';
	echo "</div></div>";
}
if(isset($_POST['save_product'])){
	

	// $file=$_SESSION['shop_name'].'_log.txt';

	if(isset($_POST['product_id'])){
		// update product

		$params=array();
		$params['in_footer'] =$_POST['in_footer'];
		$params['type'] =$_POST['type'];		
		$params['visible'] =$_POST['visible'];
		$params['has_liqvidation'] =$_POST['has_liqvidation'];
		$params['id']=$_POST['product_id'];
		$shopObj->update('products',$params);
		$last_id=$_POST['product_id'];
	}else{
		//insert product in database		
		
		$params['product_code'] ='';
		$params['brand_id'] ='';
		$params['in_footer'] =$_POST['in_footer'];
		$params['type'] =$_POST['type'];
		$params['rating'] =0;
		$params['visible'] =$_POST['visible'];
		$params['category_id'] =1;
		$params['has_liqvidation'] =$_POST['has_liqvidation'];
		$params['has_discount'] =0;
		$last_id = $shopObj->insert('products',$params);
	}
	//insert categories
	$params = array($_POST['product_id']);
	$shopObj->execute_query("DELETE FROM products_categories WHERE product_id=? ",$params);
	$categories = explode(',',$_POST['category']);
	foreach($categories as $key => $value) {
			if($value){
		 		$params = array('product_id'=>$last_id,'category_id'=>$value);
		 		$shopObj->insert('products_categories',$params);
			}
	}


	foreach ($_POST as $key => $value) {
		$parts = explode('_',$key);
		if($parts[0]=='name' || $parts[0]=='description' ){
			$values[$parts[1]][$parts[0]]=$value;
		}else if($parts[0]=='meta') { 
			$values[$parts[2]][$parts[0].'_'.$parts[1]]=$value;
		}
	}



	if(isset($_POST['product_id'])){

		//update product details
		foreach ($values as $key => $value) {
			$url =createURL('products_details',$value['name'],$shopObj);
			$params=array($value['name'],$url,$value['description'],$value['meta_description'],$value['meta_keywords'],$_POST['product_id'],$key);
			$shopObj->execute_query("UPDATE products_details SET name=?,url=? , description=?, meta_description=? , meta_keywords=? WHERE product_id=? AND language_id=?",$params);
		}

		$targetFolder='../acces_logs/';

		if (!is_dir($targetFolder)) {
			mkdir($targetFolder);
		}
		$content='----'.date("d-m-Y H:i:s").'-----'.' Produsul "'.$value['name'].' a fost modificat de catre utilizatorul cu contul '.$_SESSION['user_name'].'"\n';	
		$fp = fopen("../acces_logs/{$_SESSION['shop_name']}.txt","a");
		fwrite($fp,$content);
		fclose($fp);	

	}else{

	//insert product details in database

		foreach ($values as $key => $value) {
			$params=array();
			$params['language_id'] = $key;
			$params['product_id']=$last_id;
			$params['name']= $value['name'];
			$params['url']= createURL('products_details',$value['name'],$shopObj,1,1);
			$params['description']= $value['description'];
			$params['meta_description']= $value['meta_description'];
			$params['meta_keywords']= $value['meta_keywords'];

			$insert = $shopObj->insert('products_details',$params);

			$targetFolder='../acces_logs/';

		if (!is_dir($targetFolder)) {
			mkdir($targetFolder);
		}
		$content='----'.date("d-m-Y H:i:s").'-----'.' Produsul "'.$value['name'].'"" a fost adaugat de catre utilizatorul cu contul '.$_SESSION['user_name'].'"\n';	
		$fp = fopen("../acces_logs/{$_SESSION['shop_name']}.txt","a");
		fwrite($fp,$content);
		fclose($fp);
		}
	}

	$params=array($_POST['product_id']);
	$shopObj->execute_query("DELETE FROM product_properties WHERE product_id=?",$params);
	//save attributes and values in database
	$attributes = json_decode($_POST['attributes']);
	foreach ($attributes as $key => $value) {
		if(!isset($value)){
			unset($attributes[$key]);
		}else{

			$params = array('product_id'=>$last_id,'property_id'=>$key);
			$last_property= $shopObj->insert('product_properties',$params);
			for($i=0;$i<count($value);$i++){
				$params = array("product_property_id"=>$last_property,"property_value_id"=>$value[$i]);
				$shopObj->insert('product_properties_values',$params);
			}
		}

	}
	if(!isset($_POST['product_id'])){
		$params['internal_code']='';
		$params['barcode']='';
		$params['product_id']=$last_id;
		$params['quantity']=0;
		$params['properties']='';
		$params['buy_count']=0;
		$params['price']=0;
		$params['has_image']=0;

		$shopObj->insert('stocks',$params);
	}
	if(isset($_POST['product_id'])){
		$last_id = $_POST['product_id'];
	}
	echo '<table id="stocks_table" class="table table-striped table-bordered table-hover">
											<thead>
												<tr>	
													<th><a href="javascript:void(0)" onclick="delete_selected()">'.translate_word_shop('Delete selected',$dictionary).'</a></th>
													<th>'.translate_word_shop('Barcode',$dictionary).'</th>';
									$products_prop = $shopObj->fetch_result("SELECT product_properties.*,properties_details.name FROM product_properties,properties_details WHERE 
																	product_id='{$last_id}' AND properties_details.language_id={$active_lang} AND properties_details.property_id=product_properties.property_id ");
								
									foreach ($products_prop as $key => $value) {
										echo "<th>".ucfirst($value['name'])."</th>";
									}				
									echo		   '<th>'.translate_word_shop('Quantity',$dictionary).'</th>
													<th>'.translate_word_shop('Price',$dictionary).'</th>
													<th>'.translate_word_shop('Actions',$dictionary).'</th>
												</tr>
											<thead>
											<tbody>';
									$stocks = $shopObj->fetch_result("SELECT * FROM stocks WHERE product_id='{$last_id}'");

									foreach($stocks as $key=>$value){
										$properties_array = json_decode($value['properties'],true);
										echo "<tr>
												<td><input type='checkbox'  class='delete_selected' value='{$value['id']}'/><span class='lbl'></span></td>
												<td><input type='text'  style='width:100px' value='{$value['barcode']}' onblur='update_stock(\"barcode\",{$value['id']},this);' /></td>";

												foreach ($products_prop as $key_prop => $value_prop) {
													echo "<td>";
													$params = array($value_prop['property_id'],$active_lang);
													$properties = $shopObj->fetch_result("SELECT properties_values.id, properties_values_details.name  FROM properties_values,properties_values_details WHERE properties_values.property_id=?
																						AND properties_values.id = properties_values_details.property_value_id AND language_id=?",$params);
													
													echo "<select style='width:100px' class='stock_properties' id='{$value_prop['property_id']}' onchange='update_stock_property({$value['id']},this)'>";
													echo "<option></option>";
													foreach($properties as $property_key=>$property_value){
														echo "<option value='{$property_value['id']}' ";
														if($property_value['id'] == $properties_array[$value_prop['property_id']]){
															 echo "selected='selected'";
														}
														echo " >{$property_value['name']}</option>";
													}

													echo "</select>
															</td>";
												}		

										echo	"
												
												<td><input type='text' style='width:50px' onblur='update_stock(\"quantity\",{$value['id']},this);' value='{$value['quantity']}' /></td>
												<td><input type='text' style='width:50px' onblur='update_stock(\"price\",{$value['id']},this);'  value='{$value['price']}' /></td>
												<td>
													<a class='red' href='javascript:void(0)' onclick='delete_stock({$value['id']},this)'>
														<i class='icon-trash bigger-130'></i>
													</a>
												</td>	
											 </tr>";
									}
									echo   '</tbody>		
										</table>
										<script>product='.$last_id.'</script>';


}
if(isset($_POST['stock_field'])){
	$params=array();
	$params[$_POST['stock_field']]=$_POST['value'];
	$params['id']=$_POST['stock'];
	$shopObj->update('stocks',$params);
}
if(isset($_POST['update_stock'])){
	$values = json_decode($_POST['update_stock']);
	foreach ($values as $key => $value) {
	 	if(!$value){
	 		unset($values[$key]);
	 	}
	 } 
	$params=array();
	$params['properties']= json_encode($values);
	$params['id']=$_POST['stock_id'];
	$shopObj->update('stocks',$params);
}
if(isset($_POST['add_stock'])){
	$params=array();
	$params['internal_code']='';
	$params['barcode']='';
	$params['product_id']=$_POST['add_stock'];
	$params['quantity']=0;
	$params['properties']='';
	$params['buy_count']=0;
	$params['price']=0;
	$params['has_image']=0;

	$last_id= $shopObj->insert('stocks',$params);

	$params=array($_POST['add_stock']);
	$properties = $shopObj->fetch_result("SELECT property_id FROM product_properties WHERE product_id=?",$params);

		
	$vals[0]="<input type='checkbox'  class='delete_selected' value='{$last_id}'/><span class='lbl'>";
	$vals[1]= "<input type='text'  style='width:100px' value='' onblur='update_stock(\"barcode\",{$last_id},this);' />";	
	$i=2;
	foreach($properties as $key=>$value){

		$params = array($value['property_id'],$active_lang);

		$properties_values = $shopObj->fetch_result("SELECT properties_values.id, properties_values_details.name  FROM properties_values,properties_values_details WHERE properties_values.property_id=?
			AND properties_values.id = properties_values_details.property_value_id AND language_id=?",$params);

		$vals[$i] = "<select style='width:100px' class='stock_properties' id='{$value['property_id']}' onchange='update_stock_property({$last_id},this)'>";
		$vals[$i].='<option></option>';
		foreach($properties_values as $property_key=>$property_value){
			$vals[$i].= "<option value='{$property_value['id']}'>{$property_value['name']}</option>";
		}

		$vals[$i].= "</select>";
		$i++;
	}
	$vals[$i] = "<input type='text' style='width:50px' onblur='update_stock(\"quantity\",{$last_id},this);' value='0' />";
	$vals[$i+1] ="<input type='text' style='width:50px' onblur='update_stock(\"price\",{$last_id},this);'  value='0' />";	
	$vals[$i+2]="<a class='red' href='javascript:void(0)' onclick='delete_stock({$last_id},this)'>
														<i class='icon-trash bigger-130'></i>
													</a>";
	echo json_encode($vals);
}
if(isset($_POST['remove_stock'])){
	$params=array();
	$params['id'] = $_POST['remove_stock'];
	$shopObj->delete("stocks",$params);
}
if(isset($_POST['delete_selected_stocks'])){
	$values = explode(',', $_POST['delete_selected_stocks']);
	foreach ($values as $key => $value) {
		$params=array('id'=>$value);
		$shopObj->delete('stocks',$params);
	}
}
if(isset($_POST['add_attribute'])){
	//insert property
      $params=array('type'=>$_POST['att_type'],'show_in_filters'=>1,'show_in_admin'=>1);
      $last_id=$shopObj->insert('properties',$params);
    //  insert 
      foreach ($_POST as $key => $value) {
      	$data=array();
      	$data=explode('_', $key);
      	if($data['1']=='name'){
      		$params=array('language_id'=>$data['2'],'property_id'=>$last_id,'name'=>$value);
      		$shopObj->insert('properties_details',$params);
      	}
      }
      $attributes = $shopObj->fetch_result("SELECT properties.id,properties.type, properties_details.name FROM properties 
									JOIN properties_details ON properties.id =properties_details.property_id  
									WHERE properties_details.language_id='{$active_lang}'");
      foreach ($attributes as $key => $value) {
		echo "<option value='{$value['id']}'";
		
		echo " >{$value['name']}</option>";
	}

}
if(isset($_POST['add_property'])){
	$params = array('property_id'=>$_POST['att_select'],'value'=>$_POST['property_value']);
	$last_id=$shopObj->insert('properties_values',$params);
	foreach($_POST as $key=>$value){
		$data = explode('_', $key);
		if($data['1']=='name'){
			$url= createURL('properties_values_details',$value,$shopObj);
			$params=array('language_id'=>$data[2],'property_value_id'=>$last_id,'name'=>$value,'url'=>$url);
			$shopObj->insert('properties_values_details',$params);
		}
	}
	$params = array($_POST['att_select'],$available_lang[0]['id']);

	$properties = $shopObj->fetch_result("SELECT properties_values.id, properties_values_details.name  FROM properties_values,properties_values_details
										 WHERE properties_values.property_id=?
										AND properties_values.id = properties_values_details.property_value_id AND language_id=?",$params);

	$selected_properties_vals = $shopObj->fetch_result("SELECT product_properties_values.property_value_id FROM product_properties_values,product_properties WHERE 
														product_properties_values.product_property_id =product_properties.id AND product_properties.product_id={$_POST['pr_id']}   
														AND product_properties.property_id= {$_POST['add_property']}");

	foreach($selected_properties_vals as $prop_value){
		$sel_vals[]= $prop_value['property_value_id'];
	}
	
	echo '<select multiple="" class="chzn-select" name="properties_'.$_POST['get_properties'].'"   data-placeholder="Choose properties values...">';
	foreach ($properties as $key => $value) {
		echo "<option value='{$value['id']}'";
		if(in_array($value['id'], $sel_vals)){
			echo " selected='selected' ";
		}
		echo ">{$value['name']}</option>";
	}
	echo '</select><br /><button class="add_property_value btn btn-minier btn-success" style="margin-top:10px">+Add property value</button>';
	
}
if(isset($_POST['make_comment_visible'])){
	$params['id'] =$_POST['make_comment_visible'];
	$params['visible'] =$_POST['check'];

	$shopObj->update("comments",$params);
}
?>